package com.example.zz.example.customcontrol;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import com.example.customcontrollib.IconView;
import com.example.zz.example.App;
import com.example.zz.example.LogUtils;
import com.example.zz.example.R;
import com.example.zz.example.customcontrol.floatview.FloatScanView;

import java.lang.reflect.Method;

public class RingRectActivity extends AppCompatActivity {
    private WindowManager wm;
    private AlertDialog dialog;
    private WindowManager.LayoutParams wmParams;
    private FloatScanView fsv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i("onCreate");
        setContentView(R.layout.ring_rect_control);
        IconView iconView = findViewById(R.id.start_icon_view);

        iconView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconView.startToMove();
                Point point = new Point(0, 0);
                point = null;
                try {
                    point.getClass();
                } catch (Exception e) {
                    LogUtils.i("e = " + e);
                }
            }
        });

        Button rectToRing = findViewById(R.id.rect_to_ring);
        rectToRing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconView.ringChangeToRect(false);
            }
        });

        findViewById(R.id.ring_to_rect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconView.ringChangeToRect(true);
            }
        });

        findViewById(R.id.add_view).setOnClickListener(view -> {
            addView();
        });

    }

    private void addView() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);    //加载View视图，这个就是我们要显示的内容
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);    //获取WindowManage
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        //设置LayoutParams的属性
        layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;       //该Type描述的是形成的窗口的层级关系，下面会详细列出它的属性
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |       //该flags描述的是窗口的模式，是否可以触摸，可以聚焦等
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        layoutParams.gravity = Gravity.TOP;                                       //设置窗口的位置
        layoutParams.format = PixelFormat.TRANSLUCENT;                               //不设置这个弹出框的透明遮罩显示为黑色
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;                //窗口的宽
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;               //窗口的高
        layoutParams.x = 300;
        layoutParams.y = 1000;
//        layoutParams.token = ((View)findViewById(R.id.ring_to_rect)).getWindowToken();           //获取当前Activity中的View中的TOken,来依附Activity，因为设置了该值，纳闷写的这些代码不能出现在onCreate();否则会报错。
        windowManager.addView(view, layoutParams);                                   //显示窗口
    }

    public void addMoveFloatView(View view) {

        dialog = new AlertDialog.Builder(this)
                .setTitle("悬浮窗权限管理")
                .setMessage("是否去开启悬浮窗权限？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //打开权限设置
                        openSetting();
                    }
                })
                .setNegativeButton("否", null)
                .create();
        //创建悬浮框
        createFloatView();
    }

    private void createFloatView() {


        //开启悬浮窗前先请求权限
        if ("Xiaomi".equals(Build.MANUFACTURER)) {//小米手机
            //            LogUtil.E("小米手机");
            requestPermission();
        } else if ("Meizu".equals(Build.MANUFACTURER)) {//魅族手机
            //            LogUtil.E("魅族手机");
            requestPermission();
        } else {//其他手机
            //            LogUtil.E("其他手机");
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    startActivityForResult(intent, 12);
                } else {
                    //
                }
            } else {


            }
        }


        wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        //        wmParams = new WindowManager.LayoutParams();
        wmParams = ((App) getApplication()).getMywmParams();


        //        wmParams.type=2002;          //type是关键，这里的2002表示系统级窗口
        wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        wmParams.format = PixelFormat.RGBA_8888;//设置图片格式，效果为背景透明


        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;//
        wmParams.x = 0;
        wmParams.y = 0;
        wmParams.width = 100;
        wmParams.height = 100;
        fsv = new FloatScanView(getApplicationContext());
        fsv.setImageResource(R.mipmap.ic_launcher);
        fsv.setBackgroundColor(getResources().getColor(R.color.background_color));
        wm.addView(fsv, wmParams);
    }

    /**
     * 请求用户给予悬浮窗的权限
     */
    public void requestPermission() {
        if (isFloatWindowOpAllowed(this)) {//已经开启
        } else {
            dialog.show();
        }
    }
    /**
     * 判断悬浮窗权限
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isFloatWindowOpAllowed(Context context) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            return checkOp(context, 24);  // AppOpsManager.OP_SYSTEM_ALERT_WINDOW
        } else {
            if ((context.getApplicationInfo().flags & 1 << 27) == 1 << 27) {
                return true;
            } else {
                return false;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;


        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                Class<?> spClazz = Class.forName(manager.getClass().getName());
                Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
                int property = (Integer) method.invoke(manager, op,
                        Binder.getCallingUid(), context.getPackageName());
                Log.e("399", " property: " + property);


                if (AppOpsManager.MODE_ALLOWED == property) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.e("399", "Below API 19 cannot invoke!");
        }
        return false;
    }


    /**
     * 打开权限设置界面
     */
    public void openSetting() {
        try {
            Intent localIntent = new Intent(
                    "miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter",
                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", getPackageName());
            startActivityForResult(localIntent, 11);
            //            LogUtil.E("启动小米悬浮窗设置界面");
        } catch (ActivityNotFoundException localActivityNotFoundException) {
            Intent intent1 = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent1.setData(uri);
            startActivityForResult(intent1, 11);
            //            LogUtil.E("启动悬浮窗界面");
        }




    }



}
